import math
from json import JSONEncoder

from app.libs.init import mongo
from datetime import datetime


def save_request_record(group_id, case_list, time_c, error, space_id, run_status, _id=None):
    mongo.db.request_records.insert_one(log_formatter(group_id, case_list, time_c, error, space_id, run_status, _id))


def update_request_record(group_id, case_list, time_c, error, space_id, run_status, _id=None):
    # 查找task_id的信息 并更新数据
    # 定义要更新的文档
    update_document = log_formatter(group_id, case_list, time_c, error, space_id, run_status, _id)

    # 定义更新操作
    update_spec = {"$set": update_document}

    # 更新指定字段
    mongo.db.request_records.update_one({"task_id": _id}, update=update_spec)


def log_formatter(group_id, case_list, time_c, error, space_id, run_status, _id=None):
    data = {
        'group_id': group_id,
        'case_list': case_list,
        "create_time": datetime.now(),
        "time_consuming": time_c,
        "error": error,
        "space_id": int(space_id),
        "run_status": run_status
    }
    if _id:
        data['task_id'] = _id
    return data


#
# def delete_log_all():
#     mongo.db.request_records.drop()


def compute_time(timestamp):
    if not timestamp:
        return timestamp
    dt = format_time(timestamp)
    # 计算时间差
    delta = datetime.now() - dt
    # 根据时间差的大小展示不同的时间单位
    if delta.days > 0:
        return f"{delta.days}天前"
    elif delta.seconds >= 3600:
        hours = delta.seconds // 3600
        return f"{hours}小时前"
    elif delta.seconds >= 60:
        minutes = delta.seconds // 60
        return f"{minutes}分钟前"
    else:
        return f"{delta.seconds}秒前"


def format_time(f_time):
    if not f_time:
        return f_time
    # 将时间戳转换为datetime对象
    dt = datetime.fromtimestamp(math.floor(float(f_time)))
    return dt


def format_log(data: [list]):
    data_list = []
    if not data or not data[0]:
        return data_list
    for d in data:
        d['_id'] = str(d['_id'])
        if d['create_time']:
            dt = d['create_time']
            d['create_time'] = dt.strftime('%Y-%m-%d %H:%M:%S ')
            d['len_sum'] = len(d['case_list'])
            d['name'] = get_group_name(d['group_id'])
        data_list.append(d)

    return data_list


def get_group_name(group_id):
    from app.models.case_group import CaseGroupModel
    if not group_id:
        return None
    try:
        group = CaseGroupModel().query.filter_by(id=group_id).first_or_404()
        return group.name
    except:
        return None
